package com.shiro.distribution.redis;

import com.shiro.distribution.DistibuteCache;
import com.shiro.distribution.DistributeCacheFactory;
import org.apache.shiro.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 功能或描述：
 *
 * Package com.shiro.distribution.redis
 * Author: DR.YangLong
 * Date: 14-9-30
 * Time: 上午11:27
 * Email: 410357434@163.com
 * Version: 1.0
 * Module: 修正:            日期：
 */
public class RedisCacheFactory implements DistributeCacheFactory {
    private static Logger logger = LoggerFactory.getLogger(RedisCacheFactory.class);
    /**
     * session工厂
     */
    private JedisConnectionFactory jedisConnectionFactory;

    /**
     * 缓存存储时的key的前缀
     */
    private String cacheIdentity;

    @Override
    public void destroy() {
        jedisConnectionFactory.destroy();
    }

    @Override
    public <K, V> Cache<K, V> getCache(String name) {
        RedisTemplate<String, V> redisTemplate = new RedisTemplate<String, V>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        RedisRepository<K, V> redisRepository = new RedisRepository<K, V>(redisTemplate);
        if (!"".equals(getCacheIdentity()) && null != getCacheIdentity()) {
            redisRepository.setKeyPrefix(getCacheIdentity());
        }
        return new DistibuteCache<K, V>(redisRepository, name);
    }

    public JedisConnectionFactory getJedisConnectionFactory() {
        return jedisConnectionFactory;
    }

    public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
        this.jedisConnectionFactory = jedisConnectionFactory;
    }

    public String getCacheIdentity() {
        return cacheIdentity;
    }

    public void setCacheIdentity(String cacheIdentity) {
        this.cacheIdentity = cacheIdentity;
    }
}
